package com.tanchengjin.admin.utils;

import com.tanchengjin.admin.model.pojo.AdminOperationLog;
import com.tanchengjin.admin.service.AdminOperationLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

/**
 * 日志记录工具类
 */
@Component
public class OperationLogUtil {
    @Autowired
    AdminOperationLogService adminOperationLogService;

    @Autowired
    private static OperationLogUtil operationLogUtil;

    private static final Logger logger = LoggerFactory.getLogger(OperationLogUtil.class);

    @PostConstruct
    public void init() {
        operationLogUtil = this;
    }

    public static boolean write(HttpServletRequest request, String content) {
        try {
            AdminOperationLog adminOperationLog = new AdminOperationLog();
            adminOperationLog.setDescription(content);
            adminOperationLog.setHeaders(HttpServletRequestUtil.headersToJsonString(request));
            adminOperationLog.setIp(HttpServletRequestUtil.getCurrentIP());
            adminOperationLog.setUrl(HttpServletRequestUtil.getCurrentUrl());
            adminOperationLog.setHttpMethod(HttpServletRequestUtil.getCurrentMethod());
            adminOperationLog.setParams(HttpServletRequestUtil.paramsToJsonString(request));
            operationLogUtil.adminOperationLogService.create(adminOperationLog);
        } catch (Exception exception) {
            logger.error(exception.getMessage());
            exception.printStackTrace();
            return false;
        }
        return true;
    }
}
